package org.zoffy.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.zoffy.model.dto.PopularSiteDTO;
import org.zoffy.model.vo.PopularSiteVO;
import org.zoffy.security.UserDetail;
import org.zoffy.service.PopularSiteService;
import org.zoffy.commons.BaseResponse;
import org.zoffy.commons.ResultUtils;

import java.util.List;

@RestController
@RequestMapping("/popular-site")
@PreAuthorize("isAuthenticated()")
@RequiredArgsConstructor
public class PopularSiteController {
    private final PopularSiteService popularSiteService;

    @GetMapping("/list")
    public BaseResponse<List<PopularSiteVO>> querySites(Authentication authentication) {
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        List<PopularSiteVO> sites = popularSiteService.querySites(userDetail.getId());
        return ResultUtils.success(sites);
    }

    @PostMapping("/add")
    public BaseResponse<Long> addSite(@RequestBody PopularSiteDTO popularSiteDTO, Authentication authentication) {
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        Long siteId = popularSiteService.addSite(popularSiteDTO, userDetail.getId());
        return ResultUtils.success(siteId);
    }

    @PostMapping("/update")
    public BaseResponse<Boolean> updateSite(@RequestBody PopularSiteDTO popularSiteDTO, Authentication authentication) {
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        Boolean result = popularSiteService.updateSite(popularSiteDTO.getId(), popularSiteDTO, userDetail.getId());
        return ResultUtils.success(result);
    }

    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteSite(@RequestBody PopularSiteDTO popularSiteDTO, Authentication authentication) {
        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        Boolean result = popularSiteService.deleteSite(popularSiteDTO.getId(), userDetail.getId());
        return ResultUtils.success(result);
    }
}